package commons;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.ProtocolException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;

public class WSRequestHandler {

	/**
	 * Adds the necessary headers to the HttpsURLConnection passed in
	 * order for the call to be successful
	 */
	public static void addAuctionHTTPHeaders(HttpURLConnection connection, String soapAction) throws ProtocolException
	{
		connection.setRequestMethod("POST");
	    connection.setRequestProperty("SOAPAction", soapAction);
	    connection.setRequestProperty("Host", "api.auction.co.kr");
	    connection.setRequestProperty("Content-Type", "text/xml; charset=utf-8");
		
		connection.setDoInput(true);
		connection.setDoOutput(true);
	}

	/**
	 * Sends the request to the Server and returns the Document (XML)
	 * that is returned as the response.
	 */    
	public static Document SendRequest(HttpURLConnection connection) {
	    try
	    {
	        //Get the Input stream for the response
	        InputStream in = connection.getInputStream();
	        
	        //Get the XML file into a Document object
	        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
	        DocumentBuilder docBuild = factory.newDocumentBuilder();
	        //Get the stream into a Document object
	        Document response = docBuild.parse(in);
	        
	        //Print SOAP Response
	        System.out.println("\r\n****RESPONSE SOAP****");
	        System.out.println(response.getDocumentElement().toString().replaceAll("><", ">\r\n<"));
	        
	        //close the input stream and connection
	        in.close();
	        
	        //return the response XML Document
	        return response;
	    } catch(IOException e) {
	        System.out.println("SendRequest IO Error: " + e.toString());
	        //e.printStackTrace();
	        
	        try {
	            InputStream es = connection.getErrorStream();
	            //Get the XML file into a Document object
	            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
	            DocumentBuilder docBuild = factory.newDocumentBuilder();
	            //Get the stream into a Document object
		        Document response = docBuild.parse(es);
		        System.out.println(response.getDocumentElement());
		        
		        es.close();
	        } catch (Exception e2){}
	
	        return null;
	    } catch(Exception e) {
	        System.out.println("Error Sending Request: " + e.toString());
	        e.printStackTrace();
	        
	        return null;
	    }
	    finally {
	    	if (connection != null) connection.disconnect();
	    }
	}

}
